package com.awenhui.demo.demo.thread;

import lombok.Data;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author yuxf
 * @version 1.0
 * @date 2021/7/1 14:10
 */
public class ThreadPoolTest {
    static List<TaskDto> list = new ArrayList<>();

    static {
        for (int i = 0; i < 100; i++) {

            list.add(new TaskDto("任务" + i));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long poolStart = System.currentTimeMillis();

        //使用线程池开启10个线程进行推送
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (TaskDto taskDto : list) {
            executorService.execute(new MyPoolThread(taskDto));
        }

        executorService.shutdown();
        //调用shutdown()后阻塞直到所有线程执行完毕
        executorService.awaitTermination(1, TimeUnit.HOURS);
        long poolEnd = System.currentTimeMillis();
        System.out.println("用时" + (poolEnd - poolStart) + "ms");
    }

    /**
     * 启用多线程执行任务
     *
     * @param runnableList 任务列表
     * @param threadNum    线程数
     */
    public static void excuteTaskList(List<Runnable> runnableList, int threadNum) {
        //使用线程池开启n个线程进行推送
        ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
        runnableList.forEach(r -> executorService.execute(r));
        executorService.shutdown();
    }
}

/**
 * 推送任务的线程
 */
class MyPoolThread implements Runnable {

    private TaskDto taskDto;

    public MyPoolThread(TaskDto taskDto) {
        this.taskDto = taskDto;
    }

    @SneakyThrows
    @Override
    public void run() {
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + ":执行推送,任务名称：" + taskDto.getName());
    }
}

/**
 * 任务实体
 */
@Data
class TaskDto {
    public TaskDto(String name) {
        this.name = name;
    }

    private String name;
}
